include FileUtils

SRC_DIR = File.join(File.dirname(__FILE__), 'sources')
DEST_DIR = File.join(File.dirname(__FILE__), 'SOURCES')

def rm_svn(dir)
  cd dir do 
    system "find -name .svn|xargs rm -rf" 
  end
end

def prepare_source(label)
  src_package = File.join(DEST_DIR, "#{label}.zip")
  rm_f src_package
  
  cd SRC_DIR do
    mkdir_p "tmp"
    cp_r label, "tmp"
    rm_svn "tmp"
    cd "tmp" do
      system "zip -r #{src_package} #{label}"
    end
    rm_rf "tmp"
  end  
end

task :default => :package_all

desc 'build source package for ruby and rubygems'
task :prepare_source do
  prepare_source "ruby-1.8.5"
  prepare_source "rubygems-0.9.2"
  system %Q(echo "%_topdir #{File.dirname(__FILE__)}" > $HOME/.rpmmacros)
end

desc 'make RPM for ruby'
task :ruby_package => :prepare_source do
  system "sudo rpmbuild -bb SPECS/ruby.spec"
end

desc 'make RPM for rubygems'
task :gems_package => :prepare_source do
  system "sudo rpmbuild -bb SPECS/rubygems.spec"
end

desc 'make RPM for haproxy'
task :haproxy_package do
  cp(File.join(SRC_DIR, 'haproxy-1.3.8.2.tar.gz'), DEST_DIR)
  system "sudo rpmbuild -bb SPECS/haproxy.spec"
end

desc 'make umbrella RPM for rubyworks-common (takes long time)'
task :rubyworks_common_package => [:ruby_package, :gems_package, :haproxy_package] do 
  system "rpmbuild -bb SPECS/rubyworks-common.spec"
end

desc 'make RPM for rails-control-center'
task :control_center_package do
  prj_name = "rails-control-center"

  fakeroot = File.join(File.dirname(__FILE__), 'fakeroot')
  rm_rf fakeroot
  dest_dir = File.join(fakeroot, 'usr', 'local', 'lib', prj_name)
  mkdir_p dest_dir

  control_center_dir = File.join(File.dirname(__FILE__), 'control-center')
  cd control_center_dir do 
    system "rake clear"
  end
  
  system "cp -r #{control_center_dir}/* #{dest_dir}"
  FileUtils.cd dest_dir do
    system "rm -rf config/sites/*"
    system "rm -rf ddis/*"
    mkdir "../rails-apps"
  end

  rm_svn fakeroot
  system "rpmbuild -bb --buildroot=#{fakeroot} SPECS/rails-control-center.spec"
  rm_rf fakeroot
end

desc 'make RPM for dogfood application'
task :dogfood_package do
  cd File.join(File.dirname(__FILE__), 'dogfood') do
    system "rake rpm_package"
  end
end

task :create_repo do
  system "createrepo RPMS"
end

desc 'build the entire package'
task :rubyworks_package => [:control_center_package, :dogfood_package] do 
  system "rpmbuild -bb SPECS/rubyworks.spec"
  Rake::Task[:create_repo].invoke
end

desc 'build all packages'
task :package_all => [:rubyworks_common_package, :rubyworks_package] do
end

desc 'upload all packages'
task :upload_repo => [:create_repo] do
  system "scp -r #{File.join(File.dirname(__FILE__), 'RPMS')} gigix@repo.thoughtworkers.org:/home/gigix/repo.thoughtworkers.org"
end